package com.DHH.Controller.Api;

import com.DHH.Config.ApiConstant;
import com.DHH.Config.Constant;
import com.DHH.Entity.Base.BaseThirdpartyLogin;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Base.BaseUserInfo;
import com.DHH.Entity.Capital.CapitalSurplusMoneyRecord;
import com.DHH.Entity.Order.OrderInfo;
import com.DHH.Entity.WxOrder.WxOrderInfo;
import com.DHH.Mapper.Api.Order.ApiOrderInfoMapper;
import com.DHH.Mapper.Base.BaseThirdpartyLoginMapper;
import com.DHH.Mapper.Base.BaseUserInfoMapper;
import com.DHH.Mapper.Capital.CapitalSurplusMoneyRecordMapper;
import com.DHH.Mapper.WxOrder.WxOrderInfoMapper;
import com.DHH.Service.Api.ApiOrderServices;
import com.DHH.wx.action.Pay_Launch;
import com.DHH.wx.util.PayUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 汪玉东 on 2017/9/1.
 */
@Controller
@RequestMapping("/api/pay/")
public class wxPayController {
    @Resource
    private BaseThirdpartyLoginMapper baseThirdpartyLoginMapper;

    @Resource
    private ApiOrderInfoMapper apiOrderInfoMapper;

    @Resource
    private BaseUserInfoMapper baseUserInfoMapper;

    @Resource
    private WxOrderInfoMapper wxOrderInfoMapper;
    @Resource
    private CapitalSurplusMoneyRecordMapper capitalSurplusMoneyRecordMapper;

    @Resource
    private ApiOrderServices apiOrderServices;

    @RequestMapping("unifiedorder")
    @ResponseBody
    public JSONObject unifiedorder(String total_fee, String body,String attach, HttpSession session){
        return wxPayCreateOrder(total_fee,body,attach,1,null,session);
    }

    @RequestMapping("doposit")
    @ResponseBody
    public JSONObject doposit(String total_fee, String body, String attach, HttpSession session){
        return wxPayCreateOrder(total_fee,body,attach,2,null,session);
    }

    @RequestMapping("payForOrder")
    @ResponseBody
    public JSONObject payForOrder(Integer orderId,String total_fee, String body, String attach, HttpSession session){
        return wxPayCreateOrder(total_fee,body,attach,3,orderId,session);
    }



    private JSONObject wxPayCreateOrder(String total_fee, String body, String attach,Integer orderType,Integer orderId,HttpSession session){
        body="大灰灰共享单车";
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        BaseThirdpartyLogin baseThirdpartyLogin=new BaseThirdpartyLogin();
        baseThirdpartyLogin.setUserId(baseUser.getId());
        baseThirdpartyLogin=baseThirdpartyLoginMapper.selectOne(baseThirdpartyLogin);
        Pay_Launch pay_launch=new Pay_Launch();
        String today = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String t_no=today+PayUtil.createCode(8);

        WxOrderInfo wxOrderInfo=new WxOrderInfo();
        wxOrderInfo.setUserId(baseUser.getId());
        wxOrderInfo.setWxorderId(t_no);
        wxOrderInfo.setMoney(total_fee);
        wxOrderInfo.setOrderType(orderType);
        wxOrderInfo.setStartDatetime(new Date());
        wxOrderInfo.setIsEnd(0);
        if(orderType==3){
            wxOrderInfo.setOrderId(orderId);
        }

        wxOrderInfoMapper.insert(wxOrderInfo);
        if(wxOrderInfo.getId()==null){
            JSONObject j=new JSONObject();
            j.put("status","-2");
            return j;
        }
        try {
            JSONObject j=pay_launch.doPost1(t_no,baseThirdpartyLogin.getOpenId(),body,total_fee);
            j.put("status","1");
            return j;
        } catch (UnsupportedEncodingException e) {
            JSONObject j=new JSONObject();
            j.put("status","-1");
            return j;
        }
    }

    @RequestMapping("notice")
    @ResponseBody
    public void notice(HttpServletRequest httpRequest, HttpSession session){
        PrintWriter out = null;
        StringBuffer xmlStr = new StringBuffer();
        try {
            BufferedReader reader = httpRequest.getReader();
            String line = null;
            while ((line = reader.readLine()) != null) {
                xmlStr.append(line);
            }
         Map<String,String> map=PayUtil.xmlToMap(xmlStr.toString());
         String result_code= map.get("result_code");
         if(result_code.equals("SUCCESS")){
          String money=map.get("total_fee");
          String out_trade_no= map.get("out_trade_no");
          WxOrderInfo wxOrderInfo=new WxOrderInfo();
          wxOrderInfo.setWxorderId(out_trade_no);
          wxOrderInfo.setIsEnd(0);
//         Example example=new Example(WxOrderInfo.class);
//         example.createCriteria().andEqualTo("wxorderId",out_trade_no).andIsNull("endDatetime");
          wxOrderInfo=wxOrderInfoMapper.selectOne(wxOrderInfo);
             //wxOrderInfoMapper.selectby
            Map map1=new HashMap();
            float money1=(float)( Double.valueOf(money)/100.00);
            map1.put("userId",wxOrderInfo.getUserId());
            map1.put("money",money1);

          if(wxOrderInfo.getOrderType()==1){

              Map map2=new HashMap();
              map2.put("userId",wxOrderInfo.getUserId());
              map2.put("money",money1* ApiConstant.WX_MONEY_TIMES);
                wxOrderInfoMapper.addUserMoney(map2);
               createMoenyDoRecord(wxOrderInfo.getUserId(),1,money1* ApiConstant.WX_MONEY_TIMES,out_trade_no);

          }else{
              if(wxOrderInfo.getOrderType()==2){
                  wxOrderInfoMapper.addUsersecMoney(map1);
                  createMoenyDoRecord(wxOrderInfo.getUserId(),3,money1,out_trade_no);
              }else{
                  if(wxOrderInfo.getOrderType()==3){
                      OrderInfo orderInfo=apiOrderInfoMapper.selectByPrimaryKey(wxOrderInfo.getOrderId());
                      apiOrderServices.updateOrderComplete(orderInfo);
                  }
              }
          }
             wxOrderInfo.setEndDatetime(new Date());
             wxOrderInfo.setIsEnd(1);
          wxOrderInfoMapper.updateByPrimaryKeySelective(wxOrderInfo);
         }
        } catch (Exception e) {

        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private void createMoenyDoRecord(Integer userId, Integer type,float doMoney,String pay_id){
        BaseUserInfo   baseUserInfo=new BaseUserInfo();
        baseUserInfo.setUserId(userId);
        baseUserInfo=baseUserInfoMapper.selectOne(baseUserInfo);
        CapitalSurplusMoneyRecord capitalSurplusMoneyRecord=new CapitalSurplusMoneyRecord();

        capitalSurplusMoneyRecord.setStateId(type);
        if(type==1){
            capitalSurplusMoneyRecord.setMsg("充值");
        }
        if(type==2){
            capitalSurplusMoneyRecord.setMsg("提现");
        }
        if(type==3){
            capitalSurplusMoneyRecord.setMsg("缴纳押金");
        }
        if(type==4){
            capitalSurplusMoneyRecord.setMsg("押金退还");
        }
        capitalSurplusMoneyRecord.setSurplus(baseUserInfo.getSurplusMoney());
        capitalSurplusMoneyRecord.setOperateMoney(doMoney);
        capitalSurplusMoneyRecord.setCreateTime(new Date());
        capitalSurplusMoneyRecord.setUserId(userId);
        capitalSurplusMoneyRecord.setPayId(pay_id);
        capitalSurplusMoneyRecordMapper.insert(capitalSurplusMoneyRecord);
    }
}
